import React, { useEffect, useRef } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../stores/authStore';

interface SimplifiedProtectedRouteProps {
  children: React.ReactNode;
  requireAdmin?: boolean;
}

const SimplifiedProtectedRoute: React.FC<SimplifiedProtectedRouteProps> = ({ 
  children, 
  requireAdmin = false 
}) => {
  const { isAuthenticated, user, isLoading } = useAuthStore();
  const location = useLocation();
  const hasChecked = useRef(false);

  // 如果正在加载，显示简单的加载状态
  if (isLoading) {
    return React.createElement('div', {
      style: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        backgroundColor: '#000',
        color: '#fff'
      }
    }, '加载中...');
  }

  // 如果未认证，重定向到登录页
  if (!isAuthenticated && !hasChecked.current) {
    hasChecked.current = true;
    console.log('用户未认证，重定向到登录页');
    return React.createElement(Navigate, { 
      to: '/login', 
      state: { from: location }, 
      replace: true 
    });
  }

  // 如果需要管理员权限但用户不是管理员，重定向到首页
  if (requireAdmin && user && !user.is_superuser && !hasChecked.current) {
    hasChecked.current = true;
    console.log('需要管理员权限但用户不是管理员，重定向到首页');
    return React.createElement(Navigate, { to: '/dashboard', replace: true });
  }

  hasChecked.current = true;
  return React.createElement(React.Fragment, null, children);
};

export default SimplifiedProtectedRoute;